package com.ds.infrastructure.hyperspace.container.endpoint.connector;

import io.netty.channel.EventLoop;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author  Weishaoying
 */
@Slf4j
public class HyperspaceStreamTimer implements Runnable {

    private static final int EVENT_CAPACITY = 5000;

    private Map<String, Timeoutable> eventDataMap = new ConcurrentHashMap<>(EVENT_CAPACITY);

    public HyperspaceStreamTimer(EventLoop eventLoop, long initialDelay, long delay) {
        eventLoop.scheduleWithFixedDelay(this, initialDelay, delay, MILLISECONDS);
    }

    public void addEvent(Timeoutable event) {
        eventDataMap.putIfAbsent(event.getEventId(), event);
    }

    public void removeEvent(Timeoutable event) {
        eventDataMap.remove(event.getEventId());
    }

    @Override
    public void run() {
        try {
            if (eventDataMap.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Timeoutable>> dataIterator = eventDataMap.entrySet().iterator();
            while (dataIterator.hasNext()) {
                Timeoutable data = dataIterator.next().getValue();
                if (data.checkTimeout()) {
                    data.onTimeout();
                    dataIterator.remove();
                }
            }
        } catch (Exception e) {
            log.error("HyperspaceTimer run failed!", e);
        }
    }
}
